#include "file.hpp"

//将数据存到树中(读取数据)
void CreateGengalogyFile(FamilyTreeNode*& root,fstream& file,int depthbefore) { 
	if (file.eof()) {
		return;
	}
	int depth;
	file >> depth;
	root->person.depth = depth;
	root->depth = depth;
	file >> root->person.name;
	file >> root->person.gender;
	file >> root->person.birthday.year;
	file >> root->person.birthday.month;
	file >> root->person.birthday.day;
	file >> root->person.education;
	file >> root->person.occupation;
	file >> root->person.IsAlive;
	file >> root->person.deathday.year;
	file >> root->person.deathday.month;
	file >> root->person.deathday.day;
	file >> root->person.remarks;
	int nextdepth;
	fstream f;
	f.open("/home/abc/桌面/opencv/GenealogicalList.txt", ios::in);
	if (f.fail()) {
		cout << "error: Open file failure!" << endl;
		exit(1);
	}
	f.seekg(file.tellg());
	
	if (file.eof()) {
		return;
	}
	f >> nextdepth;
	f.close();
	if (nextdepth > depth) {
		root->leftchild = new FamilyTreeNode;
		root->leftchild->leftchild = NULL;
		root->leftchild->rightbrother = NULL;
		CreateGengalogyFile(root->leftchild, file, depth);
	}
	f.open("/home/abc/桌面/opencv/GenealogicalList.txt", ios::in);
	if (f.fail()) { 
		cout << "error: Open file failure!" << endl;
		exit(1);
	}
	f.seekg(file.tellg());

	if (file.eof()) {
		return;
	}
	f >> nextdepth;
	f.close();
	if (nextdepth == depth) {
		root->rightbrother = new FamilyTreeNode;
		root->rightbrother->leftchild = NULL;
		root->rightbrother->rightbrother = NULL;
		CreateGengalogyFile(root->rightbrother, file, depth);
	}
}

//先序遍历把树中元素存在文件中
void SaveFile(FamilyTreeNode* root, fstream& file) {
	if (root != NULL) {
		file << root->person.depth;
		file << " ";
		file << root->person.name;
		file << " ";
		file << root->person.gender;
		file << " ";
		file << root->person.birthday.year;
		file << " ";
		file << root->person.birthday.month;
		file << " ";
		file << root->person.birthday.day;
		file << " ";
		file << root->person.education;
		file << " ";
		file << root->person.occupation;
		file << " ";
		file << root->person.IsAlive;
		file << " ";
		file << root->person.deathday.year;
		file << " ";
		file << root->person.deathday.month;
		file << " ";
		file << root->person.deathday.day;
		file << " ";
		file << root->person.remarks;
		file << '\n';
	}
	if (root->leftchild != NULL) {
		SaveFile(root->leftchild, file);

	}
	if (root->rightbrother != NULL) {
		SaveFile(root->rightbrother, file);
	}
}